package com.plian.system.controller.lg;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.plian.Tools.FileTools;
import com.plian.Tools.Func;
import com.plian.Tools.StringPool;
import com.plian.Tools.base.BaseController;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.annotation.LogOperation;
import com.plian.system.common.status.CustomCode;
import com.plian.system.config.Resubmit;
import com.plian.system.dto.lg.LawDisputeSummaryDTO;
import com.plian.system.entity.lg.LawDisputeSummary;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ListResult;
import com.plian.system.model.R;
import com.plian.system.model.token.PassToken;
import com.plian.system.mybatis.search.SearchEntity;
import com.plian.system.mybatis.search.SearchParamEntiy;
import com.plian.system.mybatis.search.TokenSearch;
import com.plian.system.mybatis.support.Condition;
import com.plian.system.mybatis.support.Query;
import com.plian.system.service.lg.ILawDisputeSummaryService;
import com.plian.system.service.sys.file.FileService;
import com.plian.system.service.wf.FormWorkflowService;
import com.plian.system.vo.lg.LawDisputeSummaryVO;
import com.plian.system.vo.report.ReportReturnVO;
import com.plian.system.wrapper.lg.LawDisputeSummaryWrapper;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;

/**
 * 企业法律纠纷案件 控制器
 *
 * @author gangan
 * @since 2019-09-27
 */
@RestController
@AllArgsConstructor
@RequestMapping("api/lawdispute")
public class LawDisputeSummaryController extends BaseController {

	private ILawDisputeSummaryService lawDisputeSummaryService;

	private FormWorkflowService formWorkflowService;

	private FileService fileService;

	private LawDisputeSummaryWrapper lawDisputeSummaryWrapper;

	/**
	 * 详情
	 */
	@PostMapping("/detail")
	public R<LawDisputeSummaryVO> detail(@RequestBody LawDisputeSummary lawDispute) {
		LawDisputeSummary detail = lawDisputeSummaryService.getOne(Condition.getQueryWrapper(lawDispute));
		R objResult = new R<LawDisputeSummaryVO>(CommonCode.SUCCESS);
		LawDisputeSummaryVO lawDisputeVO = lawDisputeSummaryWrapper.entityToVO(detail);
		objResult.setPageData(lawDisputeVO);
		return objResult;
	}

	/**
	 * 分页
	 */
	@PostMapping("/list")
	public ListResult<LawDisputeSummaryVO> list(@RequestBody Query query) {
		List<SearchEntity> entityList = query.getSearch();
		if (query.getAscs()==null&&query.getDescs()==null){
			query.setDescs("create_time");
		}
		QueryWrapper<LawDisputeSummary> queryWrapper = SearchParamEntiy.getQueryWrapper(
				Condition.getQueryWrapper(new LawDisputeSummary()), entityList
		);
		TokenSearch<LawDisputeSummary> tokenSearch = new TokenSearch<>();
		tokenSearch.addTokenQuery(queryWrapper, query);

		IPage<LawDisputeSummary> pages = lawDisputeSummaryService.page(Condition.getPage(query), queryWrapper);
		ListResult<LawDisputeSummaryVO> listResult = new ListResult<>(CommonCode.SUCCESS);
		listResult.setList(lawDisputeSummaryWrapper.entityToVO(pages.getRecords()));
		listResult.setTotal(Long.valueOf(pages.getTotal()).intValue());

		return listResult;
	}


	/**
	 * 新增或修改
	 */
	@PostMapping("/submit")
	@Resubmit(delaySeconds = 0)
	@LogOperation("企业法律纠纷案件-提交")
	public R submit(@Valid @RequestBody LawDisputeSummary lawDispute) {
		if(!lawDisputeSummaryService.checkTimeSpan(lawDispute.getId(),lawDispute.getDef14(),lawDispute.getTimeSpanId(),lawDispute.getFillingUnitId())){
			return new R(CustomCode.builder().message("每个填报范围只能填报一次").code(1999).success(false).build());
		}

		if (lawDisputeSummaryService.checkIsExisted(lawDispute.getId(), lawDispute.getCode())) {
			boolean flag = lawDispute.getId() == null;
			boolean result = lawDisputeSummaryService.saveOrUpdate(lawDispute);
			HashMap<String, Object> processVariable = new HashMap<>();
			formWorkflowService.startProcessAndSimulate(String.valueOf(lawDispute.getId()),lawDispute.getFormType(),processVariable);
			if (flag){
				fileService.saveAll(String.valueOf(lawDispute.getId()), lawDispute.getDocList());
			}else {
				fileService.edit(String.valueOf(lawDispute.getId()), lawDispute.getDocList());
			}
			return result ? new R(CommonCode.SUCCESS) : new R(CommonCode.FAIL);
		} else {
			return new R(CustomCode.builder().message("单据编码已存在").code(1999).success(false).build());
		}
	}

	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@LogOperation("企业法律纠纷案件-删除")
	public R remove(@RequestBody PageData pd) {
		List<String> ids = (List<String>)pd.get("ids");
		return lawDisputeSummaryService.deleteLogic(Func.toLongList(StringUtils.join(ids, StringPool.COMMA)))
				? new R(CommonCode.SUCCESS) : new R(CommonCode.FAIL);
	}

	/** TODO DEL
	 * 企业法律纠纷案件情况汇总
	 * @param lawDisputeDTO
	 * @return
	 */
	@PostMapping("/lawDisputeSummary")
	public R<ReportReturnVO> lawDisputeSummary(@RequestBody LawDisputeSummaryDTO lawDisputeDTO) {
		ReportReturnVO reportReturnVO = lawDisputeSummaryService.lawDisputeSummary(lawDisputeDTO);
		R<ReportReturnVO> results = new R<>(CommonCode.SUCCESS);
		results.setPageData(reportReturnVO);
		return results;
	}
//
//	/**
//	 * 企业法律纠纷案件未结案件情况汇总
//	 * @param lawDisputeDTO
//	 * @return
//	 */
//	@PostMapping("/unclosedCasesSummary")
//	public R<ReportReturnVO> unclosedCasesSummary(@RequestBody LawDisputeSummaryDTO lawDisputeDTO) {
//		ReportReturnVO reportReturnVO = lawDisputeSummaryService.unclosedCasesSummary(lawDisputeDTO);
//		R<ReportReturnVO> results = new R<>(CommonCode.SUCCESS);
//		results.setPageData(reportReturnVO);
//		return results;
//	}
//
	/**
	 * 输出pdf
	 */
	@GetMapping("/buildpdf/{id}")
	@PassToken
	public ResponseEntity<FileSystemResource> buildpdf(@PathVariable Long id) {
		return FileTools.exportPdf(lawDisputeSummaryService.buildpdf(id));
	}
}
